#pragma once
#include <iostream>
#include <vector>
#include <semaphore.h>
#include <pthread.h>

const static int defaultcap = 5;

//环形任务队列
template<class T>
class RingQueue{
private:
    //信号量减减
    void P(sem_t &sem)
    {
        sem_wait(&sem);
    }

    //信号量加加
    void V(sem_t &sem)
    {
        sem_post(&sem);
    }

    //加锁
    void Lock(pthread_mutex_t &mutex)
    {
        pthread_mutex_lock(&mutex);
    }

    //解锁
    void Unlock(pthread_mutex_t &mutex)
    {
        pthread_mutex_unlock(&mutex);
    }

public:
    //构造
    RingQueue(int cap = defaultcap)
    :ringqueue_(cap), cap_(cap), c_step_(0), p_step_(0)
    {
        //信号量初始化
        sem_init(&cdata_sem_, 0, 0);
        sem_init(&pspace_sem_, 0, cap);

        //锁初始化
        pthread_mutex_init(&c_mutex_, nullptr);
        pthread_mutex_init(&p_mutex_, nullptr);
    }

    //放入任务
    void Push(const T &in) // 生产
    {
        P(pspace_sem_); //空间信号量减减

        Lock(p_mutex_); //加生产者锁

        //放入任务，生产者下标加加，模保持环形
        ringqueue_[p_step_] = in;
        p_step_++;
        p_step_ %= cap_;

        Unlock(p_mutex_); //解生产者锁

        V(cdata_sem_); //数据信号量加加
    }

    //拿出任务
    void Pop(T *out)       
    {
        P(cdata_sem_); //数据信号量减减

        Lock(c_mutex_); //加消费者锁

        //取出任务，消费者下标加加，模保持环形
        *out = ringqueue_[c_step_];
        c_step_++;
        c_step_ %= cap_;

        Unlock(c_mutex_); //解消费者锁

        V(pspace_sem_); //空间信号量加加
    }

    //析构
    ~RingQueue()
    {
        //信号量销毁
        sem_destroy(&cdata_sem_);
        sem_destroy(&pspace_sem_);

        //锁销毁
        pthread_mutex_destroy(&c_mutex_);
        pthread_mutex_destroy(&p_mutex_);
    }

private:
    std::vector<T> ringqueue_; //利用数组配合模运算模拟环形队列
    int cap_; //队列大小

    int c_step_;       // 消费者下标
    int p_step_;       // 生产者下标

    sem_t cdata_sem_;  // 消费者关注的数据资源
    sem_t pspace_sem_; // 生产者关注的空间资源

    pthread_mutex_t c_mutex_; //消费者的锁
    pthread_mutex_t p_mutex_; //生产者的锁
};